//
//  HEMessageListViewController.m
//  huien
//
//  Created by yiban on 2017/5/31.
//  Copyright © 2017年 lcb. All rights reserved.
//

#import "HEMessageListViewController.h"
#import "Html5ViewController.h"
@interface HEMessageListViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    
}
@property(nonatomic,strong)LcbUITableView *lcbTableView;
@property(nonatomic,strong)NSMutableArray *messageArray;
@property(nonatomic,strong)NSMutableArray *selectorPatnArray;
@property(nonatomic,strong)UIView *editView;
@property(nonatomic,strong)UIButton *readButton;
@property(nonatomic,strong)UIButton *deleteButton;
@end

@implementation HEMessageListViewController
@synthesize lcbTableView=_lcbTableView;
@synthesize messageArray=_messageArray;
@synthesize selectorPatnArray=_selectorPatnArray;
@synthesize editView=_editView;
@synthesize readButton=_readButton;
@synthesize deleteButton=_deleteButton;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"系统消息";
    if (!_messageArray) {
        _messageArray =[[NSMutableArray alloc] init];
    }
    if (!_selectorPatnArray) {
        _selectorPatnArray =[[NSMutableArray alloc] init];
    }
    [self initTableView];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc
{
    if (_lcbTableView) {
        [_lcbTableView removeFromSuperview];
        _lcbTableView=nil;
    }
    
    [LcbLog log:@"HEMessageListViewController--------->dealloc"];
}
#pragma mark - tableview delegate
-(void)initTableView
{
    //
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 20, 60, 44);
    backButton.tag =100;
    [backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [backButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:backButton];
    UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    editButton.frame = CGRectMake(SCREEN_WIDTH-60, 20, 60, 44);
    editButton.tag =101;
    editButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [editButton setTitleColor:tabcolor forState:UIControlStateNormal];
    [editButton setTitle:@"编辑" forState:UIControlStateNormal];
    [editButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerView addSubview:editButton];
    
    //
    if (_lcbTableView) {
        [_lcbTableView removeFromSuperview];
        _lcbTableView=nil;
    }
    _lcbTableView =[[LcbUITableView alloc] initWithFrame:CGRectMake(0, YB_HeaderHeight, SCREEN_WIDTH, SCREEN_HEIGHT-YB_HeaderHeight) style:UITableViewStylePlain];
    _lcbTableView.dataSource=self;
    _lcbTableView.delegate=self;
    _lcbTableView.backgroundColor=[UIColor clearColor];
    _lcbTableView.allowsMultipleSelectionDuringEditing = YES;
    _lcbTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_lcbTableView];
    
}
-(UIView*)editView
{
    if (!_editView) {
        _editView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        _editView.backgroundColor =[UIColor whiteColor];
        [self.view addSubview:_editView];
        
        UIView *line1 =[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.5)];
        line1.backgroundColor=linecolor;
        [_editView addSubview:line1];
        line1=nil;
        
        _readButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _readButton.frame = CGRectMake(0, 5, SCREEN_WIDTH/2, 30);
        _readButton.tag =102;
        _readButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_readButton setTitleColor:h1color forState:UIControlStateNormal];
        [_readButton setTitle:@"全部已读" forState:UIControlStateNormal];
        [_readButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_editView addSubview:_readButton];
        UIView *line =[[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/2, 3, 1, 34)];
        line.backgroundColor=linecolor;
        [_editView addSubview:line];
        line=nil;
        
        _deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _deleteButton.frame = CGRectMake(SCREEN_WIDTH/2, 5, SCREEN_WIDTH/2, 30);
        _deleteButton.tag =103;
        _deleteButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [_deleteButton setTitleColor:h1color forState:UIControlStateNormal];
        [_deleteButton setTitle:@"删除" forState:UIControlStateNormal];
        [_deleteButton addTarget:self action:@selector(clickNavEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_editView addSubview:_deleteButton];
        
       
        
    }
    return _editView;
}
-(void)clickNavEvent:(id)sender
{
    UIButton *btn =(UIButton*)sender;
    switch (btn.tag) {
        case 100:
        {
            if (self.navigationController) {
                if (self.navigationController.viewControllers.count == 1) {
                    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                } else {
                    [self.navigationController popViewControllerAnimated:YES];
                }
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
        }
            break;
        case 101:
        {
            if (_lcbTableView && self.messageArray.count>0) {
                [_selectorPatnArray removeAllObjects];
                [_lcbTableView setEditing:!_lcbTableView.isEditing animated:YES];
                if (_lcbTableView.isEditing) {
                    self.editView.frame=CGRectMake(0, SCREEN_HEIGHT-40, SCREEN_WIDTH, 40);
                    self.lcbTableView.frame =CGRectMake(0, YB_HeaderHeight, SCREEN_WIDTH, SCREEN_HEIGHT-YB_HeaderHeight-40);
                }else{
                    self.editView.frame=CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 40);
                    self.lcbTableView.frame =CGRectMake(0, YB_HeaderHeight, SCREEN_WIDTH, SCREEN_HEIGHT-YB_HeaderHeight);
                }
                
            }
            
        }
            break;
        case 102:
        {
            if (self.lcbTableView.editing)
            {
                for (int i = 0; i < self.messageArray.count; i++) {
                    
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [self.lcbTableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionBottom];
                }
                [self.selectorPatnArray removeAllObjects];
                [self.selectorPatnArray addObjectsFromArray:self.messageArray];
                NSMutableString *ids = [NSMutableString string];
                for (SystemMessageModel *message in self.selectorPatnArray) {
                    if (message.isread==0) {
                        [ids appendString:[NSString stringWithFormat:@"%ld,",message.Id]];
                    }
                }
                if (ids.length>0) {
                    NSString *cccc = [ids substringToIndex:[ids length] - 1];
                    [self readMessage:cccc];
                }else{
                    [_lcbTableView setEditing:NO animated:YES];
                    self.editView.frame=CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 40);
                    [YBToast showWithText:@"已全部阅读！"];
                }
            }

            
        }
            break;
        case 103:
        {
            if (self.lcbTableView.editing) {
                //删除
                
                [self.messageArray removeObjectsInArray:self.selectorPatnArray];
                [self.lcbTableView reloadData];
            
                self.deleteButton.selected = NO;
                // 你的网络请求
                NSMutableString *ids = [NSMutableString string];
                for (SystemMessageModel *message in self.selectorPatnArray) {
                    [ids appendString:[NSString stringWithFormat:@"%ld,",message.Id]];
                }
                if (ids.length>0) {
                    NSString *cccc = [ids substringToIndex:[ids length] - 1];
                    [self deleteMessage:cccc];
                }else
                {
                    [YBToast showWithText:@"请选择需要删除的消息！"];
                }
               
                
            }
        }
            break;
        default:
            break;
    }
    
    
}
//
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messageArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageListCell"];
    if (cell == nil) {
        cell = [[UITableViewCell  alloc]initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:@"MessageListCell"];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIView *line =[[UIView alloc] initWithFrame:CGRectMake(10, 59, SCREEN_WIDTH, 1)];
        line.backgroundColor=linecolor;
        [cell.contentView addSubview:line];
        line=nil;
    }
    SystemMessageModel *message =[self.messageArray objectAtIndex:indexPath.row];
    if (message.isread==0) {
        cell.imageView.image = [UIImage imageNamed:@"messagelist_new"];
    }else{
        cell.imageView.image = [UIImage imageNamed:@"messagelist"];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%@ %@",message.title,message.context];
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
   return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

#pragma mark <UITableViewDelegate>
//取消选中
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row>=self.messageArray.count) {
        return;
    }
    SystemMessageModel *message =[self.messageArray objectAtIndex:indexPath.row];
    [self.selectorPatnArray removeObject:message];
    
}
//选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row>=self.messageArray.count) {
        return;
    }
    if (_lcbTableView.isEditing)
    {
        SystemMessageModel *message =[self.messageArray objectAtIndex:indexPath.row];
        [self.selectorPatnArray addObject:message];
    }else
    {
        SystemMessageModel *message =[self.messageArray objectAtIndex:indexPath.row];
        Html5ViewController *h5 =[[Html5ViewController alloc] initWithUrlString:[NSString stringWithFormat:@"%@/mobileMember/message?id=%ld&isread=%ld",[LcbDevice sharedLcbDevice].domain,message.Id,message.isread] titleString:@"消息详情"];
        [self.navigationController pushViewController:h5 animated:YES];
    }
    
}
-(void)loadData
{
    SessionModel *sessionModel =[HEShare sessionModel];
    __weak typeof (self) wSelf = self;
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:sessionModel.sessionId forKey:@"sessionId"];
    [dict setValue:[NSString stringWithFormat:@"%ld",sessionModel.session_user.userId] forKey:@"userId"];
    
    [HEApi systemMessageWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
        if (response) {
            if ([response isKindOfClass:[LcbBaseModel class]]) {
                LcbBaseModel *baseModel = (LcbBaseModel*)response;
                [[NativeRouter sharedNativeRouter] codeHander:wSelf params:baseModel completion:nil];
            }else if ([response isKindOfClass:[NSArray class]]) {
                wSelf.messageArray = (NSMutableArray*)response;
                [wSelf.lcbTableView reloadData];
            }
        }
        
    }];
}
-(void)deleteMessage:(NSString*)ids
{
    if (ids.length==0) {
        return;
    }
    SessionModel *sessionModel =[HEShare sessionModel];
    __weak typeof (self) wSelf = self;
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:sessionModel.sessionId forKey:@"sessionId"];
    [dict setValue:[NSString stringWithFormat:@"%ld",sessionModel.session_user.userId] forKey:@"userId"];
    [dict setValue:ids forKey:@"ids"];
    
    [HEApi systemMessageDeleteWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
        if (response) {
            if ([response isKindOfClass:[LcbBaseModel class]]) {
                LcbBaseModel *baseModel = (LcbBaseModel*)response;
                if (baseModel.code==0) {
                    [YBToast showWithText:baseModel.message];
                    [_lcbTableView setEditing:NO animated:YES];
                    wSelf.editView.frame=CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 40);
                }else{
                   [[NativeRouter sharedNativeRouter] codeHander:wSelf params:baseModel completion:nil];
                }
            }
        }
        
    }];
}
-(void)readMessage:(NSString*)ids
{
    if (ids.length==0) {
        return;
    }
    SessionModel *sessionModel =[HEShare sessionModel];
    __weak typeof (self) wSelf = self;
    NSMutableDictionary *dict =[NSMutableDictionary dictionary];
    [dict setValue:sessionModel.sessionId forKey:@"sessionId"];
    [dict setValue:ids forKey:@"ids"];
    [dict setValue:[NSString stringWithFormat:@"%ld",sessionModel.session_user.userId] forKey:@"userId"];
    
    [HEApi systemMessageReadWithParam:dict serviceblock:^(id response, NSString *errorMsg) {
        if (response) {
            if ([response isKindOfClass:[LcbBaseModel class]]) {
                LcbBaseModel *baseModel = (LcbBaseModel*)response;
                if (baseModel.code==0) {
                    [YBToast showWithText:baseModel.message];
                     [_lcbTableView setEditing:NO animated:YES];
                     wSelf.editView.frame=CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 40);
                     [wSelf loadData];
                }else{
                    [[NativeRouter sharedNativeRouter] codeHander:wSelf params:baseModel completion:nil];
                }
            }
        }
        
    }];
}
@end
